import _ from 'lodash';

const STORAGE_KEY = 'multRun';

let store = {
    fetch: function() {
        let todos = JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]');
        return todos;
    },

    save: function(todos) {
        localStorage.setItem(STORAGE_KEY, JSON.stringify(todos));
    },

    add: function(route) {
        let old = store.fetch();
        // 如果没有则添加
        let result = old.filter(item => {
            return item.path === route.path;
        });
        if (result.length > 0) {
            return false;
        } else {
            old.push(route);
            store.save(old);
            return true;
        }
    },

    del: function(path) {
        let old = store.fetch();
        let tmp = old.filter(item => {
            return item.path !== path;
        });
        store.save(tmp);
    }
};

const components = {};

const addComponent = function(comps) {
    for (let name in comps) {
        components[name] = comps[name];
    }
    this.init();
};

const addRouter = function(path, compName, id, query, props) {
    let name = compName;
    let comp = this.components[compName];

    if (!notFoundComponent(comp, compName)) {
        return false;
    }

    let component = Object.assign({}, _.cloneDeep(comp), {
        name: name + '-' + id,
        id: id
    });

    let route = {
        id: id,
        path: path,
        name: name + '-' + id,
        compName: compName,
        props: props
    };

    if (store.add(route)) {
        this.$router.addRoutes([
            {
                ...route,
                component: component
            }
        ]);
    }

    this.$router.push({ path, query });
};

const init = function() {
    let routes = this.store.fetch();

    routes.map(route => {
        let comp = this.components[route.compName];
        // 如果组件不存在就报错
        notFoundComponent(comp, route.compName);
        route.component = Object.assign({}, _.cloneDeep(comp), {
            name: route.name,
            id: route.id
        });
        return route;
    });
    this.$router.addRoutes(routes);
};

const multRun = {};

Object.assign(multRun, {
    store,
    components,
    addComponent,
    addRouter,
    init
});

const notFoundComponent = function(comp, compName) {
    if (!comp) {
        console.error(`multRun: 找不到"${compName}"命名的组件, \n已定义组件列表:`, components);
        return false;
    } else {
        return true;
    }
};

multRun.install = function(Vue, options) {
    Vue.multRun = Vue.prototype.$multRun = multRun;
    multRun.$router = options.router;
    multRun.components = options.components;
    multRun.init();
};

export default multRun;
